package com.example.softbank;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {

	private String ip;
	private int port;
	private String requestMessage;

	public SocketClient(String ip, int port, String requestMessage) {
		this.ip = ip;
		this.port = port;
		this.requestMessage = requestMessage;
	}

	public String sendMessage() {
		OutputStream out = null;
		InputStream in = null;
		Socket s = null;
		String responseData = "";
		try {
			s = new Socket(ip, port);
			in = s.getInputStream();
			out = s.getOutputStream();
			byte[] outData = requestMessage.getBytes("GBK");
			System.out.println(requestMessage + "===============");
			out.write(outData, 0, outData.length);
			out.flush();
			responseData = ReadInputSteamUtil.parse(in, "GBK");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (s != null) {
					s.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseData;
	}
}
